package com.klikmee.sms.core.base.communicator.vip;

import java.text.MessageFormat;

import org.apache.log4j.Logger;

import com.klikmee.sms.core.base.communicator.SendSmsIntercepter;
import com.klikmee.sms.core.base.dao.OutgoingMessageDAO;
import com.klikmee.sms.core.model.OutgoingMessage;

public class AddSequenceNumberIntercepterImpl implements SendSmsIntercepter {

	/**
	 * Log impl reference
	 */
	private Logger				logger				= Logger.getLogger(AddSequenceNumberIntercepterImpl.class);
	/**
	 * Reference to outgoing message dao used to find sequence number
	 */
	private OutgoingMessageDAO	outgoingMessageDAO	= null;

	@Override
	public void processMessage(OutgoingMessage outgoingMessage) {
		// for vip provider reference id is stored in
		// outgoingmessage.providersMessageId property
		String referenceId = outgoingMessage.getProvidersMesssageId();
		Long sequenceNumber = this.outgoingMessageDAO.findNumberOfMessagesByProviderAndProvidersMessageId(outgoingMessage.getProvider(), referenceId);

		String newReferenceId = generateVipBillingId(referenceId, sequenceNumber);

		outgoingMessage.setProvidersMesssageId(newReferenceId);

		logger.info(MessageFormat.format("Modified provider's message id of the message [{0}] to the value of [{1}]", outgoingMessage.getId().toString(), outgoingMessage.getProvidersMesssageId()));

	}

	/**
	 * Helper method for constructing vip billing Id for charged messages.
	 * 
	 * @param referenceId
	 * @param sequenceNumber
	 * @return referenceId appended by the sequenceId
	 */
	public String generateVipBillingId(String referenceId, Long sequenceNumber) {

		StringBuilder builder = new StringBuilder(referenceId);
		// check if billing id has already been set
		int indexOfMinus = referenceId.indexOf("-");
		if (indexOfMinus != -1) {
			// in this case remove number after - and set a new one
			builder.replace(indexOfMinus + 1, indexOfMinus + 2, sequenceNumber.toString());
		} else {
			// just append - [seq number]
			builder.append("-").append(sequenceNumber.toString());
		}

		return builder.toString();
	}

	public void setOutgoingMessageDAO(OutgoingMessageDAO outgoingMessageDAO) {
		this.outgoingMessageDAO = outgoingMessageDAO;
	}

}
